package cn.acewill.yxd.yunxundian;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mobstat.StatService;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.videogo.openapi.EZOpenSDK;

import org.xutils.DbManager;
import org.xutils.x;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.acewill.yxd.yunxundian.ui.user.MyNotifictionService;
import cn.acewill.yxd.yunxundian.utils.GlideImageLoader;
import cn.acewill.yxd.yunxundian.utils.GlidePauseOnScrollListener;
import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.PauseOnScrollListener;
import cn.finalteam.galleryfinal.ThemeConfig;
import okhttp3.OkHttpClient;

/**
 * Created by he on 2017/3/24.
 */
public class YXDAPP extends MultiDexApplication {

    private DbManager.DaoConfig daoConfig;
    public DbManager.DaoConfig getDaoConfig() {
        return daoConfig;
    }
    public static String token="";
    private static YXDAPP instance;
    public static FunctionConfig functionConfig = null;
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
        this.instance = this;
    }

    public static YXDAPP getInstance() {
        return instance;
    }
    public static EZOpenSDK getOpenSDK() {
        return EZOpenSDK.getInstance();
    }
    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        x.Ext.setDebug(true); // 是否输出debug日志
        SpeechUtility.createUtility(this, SpeechConstant.APPID +"=591beb26");
        SDKInitializer.initialize(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        daoConfig = new DbManager.DaoConfig()
                .setDbName("yxd.db")
                // 不设置dbDir时, 默认存储在app的私有目录.
                //.setDbDir(new File("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
                .setDbVersion(2)
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        // 开启WAL, 对写入加速提升巨大
                        db.getDatabase().enableWriteAheadLogging();
                    }
                })
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        // TODO: ...
                        // db.addColumn(...);
                        // db.dropTable(...);
                        // ...
                        // or
                        // db.dropDb();

                    }
                });

        try {
            PushAgent mPushAgent = PushAgent.getInstance(this);
            mPushAgent.setDebugMode(false);
            //注册推送服务，每次调用register方法都会回调该接口
            mPushAgent.register(new IUmengRegisterCallback() {

                @Override
                public void onSuccess(String deviceToken) {
                    //注册成功会返回device token
                    Log.d("Umsg", deviceToken);
                    //updateUpushToken
                    token = deviceToken;
                    //Toast.makeText(UpushTest.this, deviceToken, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(String s, String s1) {
                    Log.d("UmsgDT", "s=" + s + ";s1=" + s1);
                    //Toast.makeText(UpushTest.this, s1, Toast.LENGTH_SHORT).show();
                }
            });
        }
        catch (Exception e)
        {

        }

    //    GallerySet(9,this);

        //日志，发布删除
        EZOpenSDK.showSDKLog(true);

        /*设置是否支持P2P取流,详见api
                */
        EZOpenSDK.enableP2P(false);
        /** APP_KEY请替换成自己申请的
         */
        EZOpenSDK.initLib(this, "0b60455cdea347bb89353c81555457e1","");
        /*配置gallery*/

        //    配置检查服务的广播，防止服务被kill,每分钟检查service是否被关闭
        IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
        MyBroadcastReceiver receiver = new MyBroadcastReceiver();
        registerReceiver(receiver,filter);

    }

    public static void GallerySet(int value,Context context){
        ThemeConfig themeConfig=ThemeConfig.CYAN;
//        ThemeConfig themeConfig = new ThemeConfig.Builder()
//                .setTitleBarBgColor(R.color.blue)
//                .setTitleBarTextColor(R.color.white)
//                .setCheckSelectedColor(R.color.blue)
//                .setFabPressedColor(R.color.colorPrimaryDark)
//                .setFabNornalColor(R.color.blue)
//                .build();
        //配置功能
        functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(true)
                .setMutiSelectMaxSize(value)
                .setCropSquare(true)
                .build();
        ImageLoader imageLoader=new GlideImageLoader();
        PauseOnScrollListener pauseOnScrollListener=new GlidePauseOnScrollListener(false,true);
        CoreConfig coreConfig=new CoreConfig.Builder(context,imageLoader,themeConfig)
                .setFunctionConfig(functionConfig)
                .setPauseOnScrollListener(pauseOnScrollListener)
                .setNoAnimcation(false)
                .build();
        GalleryFinal.init(coreConfig);
    }

    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            //设置请求超时
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            OkHttpClient okHttpClient = builder.connectTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS).build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    String TAG = "isserverrunning";
    class MyBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //检查服务是否停止
            if(intent.getAction().equals(Intent.ACTION_TIME_TICK)){
                //还在运行
                if (isServiceRunning(context)){
                    Log.e(TAG,"onRecevie:true");
                }
                if (!isServiceRunning(context)){
                    Log.e(TAG,"onRecevie:false");
                    Intent i = new Intent(context, MyNotifictionService.class);
                    context.startService(i);
                }
            }
        }
    }





    public static boolean isServiceRunning(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            Log.e("serviceName",service.service.getClassName()+"");
            if ("cn.acewill.yxd.yunxundian.ui.user.MyNotifictionService".equals(service.service.getClassName())) {
                Log.e("isserverrunning","jinlaile");
                return true;
            }
        }
        return false;
    }



}
